package com.hqd.ch03.v50.boot.context.properties;

import com.hqd.ch03.utils.ClassUtils;
import com.hqd.ch03.v50.beans.factory.BeanCreationException;

public class ConfigurationPropertiesBindException extends BeanCreationException {

    private final ConfigurationPropertiesBean bean;

    public ConfigurationPropertiesBindException(ConfigurationPropertiesBean bean, Exception cause) {
        super(bean.getName(), getMessage(bean), cause);
        this.bean = bean;
    }

    private static String getMessage(ConfigurationPropertiesBean bean) {
        ConfigurationProperties annotation = bean.getAnnotation();
        StringBuilder message = new StringBuilder();
        message.append("Could not bind properties to '");
        message.append(ClassUtils.getShortName(bean.getType())).append("' : ");
        message.append("prefix=").append(annotation.prefix());
        message.append(", ignoreInvalidFields=").append(annotation.ignoreInvalidFields());
        message.append(", ignoreUnknownFields=").append(annotation.ignoreUnknownFields());
        return message.toString();
    }

    /**
     * Return the bean type that was being bound.
     *
     * @return the bean type
     */
    public Class<?> getBeanType() {
        return this.bean.getType();
    }

    /**
     * Return the configuration properties annotation that triggered the binding.
     *
     * @return the configuration properties annotation
     */
    public ConfigurationProperties getAnnotation() {
        return this.bean.getAnnotation();
    }

}
